package com.wise.site.main;

import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;
import com.wise.site.R;
import com.wise.site.protocol.action.LoginAction;
import com.wise.site.protocol.base.ProtocolManager;
import com.wise.site.protocol.base.SoapAction.ACTION_TYPE;
import com.wise.site.protocol.base.SoapAction.ActionListener;
import com.wise.site.protocol.result.LoginResult;
import com.wise.site.utils.Constanct;
import com.wise.site.utils.DataCache;
import com.wise.site.utils.ImageLoader;
import com.wise.site.utils.QQWeiboUtil;
import com.wise.site.utils.SinaWeiboUtil;
import com.wise.site.utils.ImageLoader.Imager;
import com.wise.site.widget.MyImageButton;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {

	// private Button register;
	private int GONE = 8;
	private int VISIBLE = 0;
	private LoginAction mLgoinAction;
	private LoginAction mReginstAction;

	private MyImageButton qqWeiboImageButton;
	private MyImageButton sinaWeiboImageButton;
	private boolean qqWeiboLogined;
	private boolean sinaWeiboLogined;
	private ProgressDialog mProgressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_login);
		qqWeiboImageButton = (MyImageButton) findViewById(R.id.txbutton);
		sinaWeiboImageButton = (MyImageButton) findViewById(R.id.sinabutton);
		findViewById(R.id.register).setOnClickListener(this);
		findViewById(R.id.login).setOnClickListener(this);
		findViewById(R.id.member_refer).setOnClickListener(this);
		findViewById(R.id.member_shop).setOnClickListener(this);
		findViewById(R.id.member_buy).setOnClickListener(this);
		findViewById(R.id.member_product).setOnClickListener(this);
		findViewById(R.id.member_logout_btn).setOnClickListener(this);
		qqWeiboImageButton.setOnClickListener(this);
		sinaWeiboImageButton.setOnClickListener(this);

		mReginstAction = new LoginAction(ACTION_TYPE.ACTION_COMMON, "register");

		mLgoinAction = new LoginAction(ACTION_TYPE.ACTION_COMMON, "chklogin");
		mLgoinAction.setActionListener(new ActionListener<LoginResult>() {

			@Override
			public void onSucceed(LoginResult result) {
				if (result.flag == 1) {
					findViewById(R.id.login_pre).setVisibility(GONE);
					findViewById(R.id.login_after).setVisibility(VISIBLE);

					DataCache.getInstance()
							.put(Constanct.ISLOGINED_KEY, result);
					ImageLoader.getInstance().DisplayImage(
							new Imager(result.portraitImageUrl,
									(ImageView) findViewById(R.id.user_face),
									0, 0));
					((TextView) findViewById(R.id.user_name))
							.setText(result.nickname);
					((TextView) findViewById(R.id.user_level))
							.setText(result.levelNmae);
				} else {
					Toast.makeText(LoginActivity.this, result.msg,
							Toast.LENGTH_LONG).show();
				}
				
				if(mProgressDialog.isShowing()){
					mProgressDialog.dismiss();
				}
			}

			@Override
			public void onError(int resultCode) {
				if(mProgressDialog.isShowing()){
					mProgressDialog.dismiss();
				}
				Toast.makeText(LoginActivity.this, "连接超时", Toast.LENGTH_LONG)
						.show();
			}

		});

		refreshSinaWeiboLoginState();
	}

	private void reginstUser() {
		String username = ((EditText) findViewById(R.id.loginname)).getText()
				.toString();
		String password = ((EditText) findViewById(R.id.password)).getText()
				.toString();
		String confirm = ((EditText) findViewById(R.id.confirmpassword))
				.getText().toString();
		
		if(!username.matches("[0-9]*")){
			Toast.makeText(this, "账号需要是手机号码", Toast.LENGTH_LONG).show();
			return;
		}
		
		if(password.length() < 6 || !password.matches("[a-zA-Z0-9]*")){
			Toast.makeText(this, "密码需要6-20个英文字母或数字", Toast.LENGTH_LONG).show();
			return;
		}

		if (password.equals(confirm)) {
			showProgress();
			mReginstAction.setUserName(username);
			mReginstAction.setPassword(password);
			mReginstAction.setActionListener(new ActionListener<LoginResult>() {

				@Override
				public void onSucceed(LoginResult result) {
					if (result.flag == 1) {
						Toast.makeText(LoginActivity.this, "注册成功",
								Toast.LENGTH_LONG).show();
						toLogin();
						if(mProgressDialog.isShowing()){
							mProgressDialog.dismiss();
						}
						// findViewById(R.id.login_pre).setVisibility(GONE);
						// findViewById(R.id.login_after).setVisibility(VISIBLE);
						//
						// DataCache.getInstance().put(Constanct.ISLOGINED_KEY,
						// result);
						// ImageLoader.getInstance().DisplayImage(new
						// Imager(result.portraitImageUrl,
						// (ImageView)findViewById(R.id.user_face), 0, 0));
						// ((TextView)findViewById(R.id.user_name)).setText(result.nickname);
						// ((TextView)findViewById(R.id.user_level)).setText(result.levelNmae);
					} else {
						Toast.makeText(LoginActivity.this, result.msg,
								Toast.LENGTH_LONG).show();
						if(mProgressDialog.isShowing()){
							mProgressDialog.dismiss();
						}
					}
				}

				@Override
				public void onError(int resultCode) {
				}

			});
			ProtocolManager.getProtocolManager().submitAction(mReginstAction);
		} else {
			Toast.makeText(this, "密码输入不同", Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.register:
			setContentView(R.layout.activity_more_register);
			findViewById(R.id.haveaccount).setOnClickListener(this);
			findViewById(R.id.finished).setOnClickListener(this);

			break;
		case R.id.haveaccount:
			toLogin();
			break;
		case R.id.login:
			String usernameStr = ((EditText) findViewById(R.id.loginname_l)).getText().toString().trim();
			String passwordStr = ((EditText) findViewById(R.id.password_l)).getText().toString().trim();
			mLgoinAction.setUserName(usernameStr);
			mLgoinAction.setPassword(passwordStr);
			showProgress();
			ProtocolManager.getProtocolManager().submitAction(mLgoinAction);
			((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
			break;

		case R.id.member_refer:
			Intent intentrefer = new Intent(this, ReferActivity.class);
			intentrefer.putExtra(Constanct.INTENT_COLLECTOR, 0);
			startActivity(intentrefer);
			break;
		case R.id.member_shop:
			Intent intentshop = new Intent(this, ReferActivity.class);
			intentshop.putExtra(Constanct.INTENT_COLLECTOR, 3);
			startActivity(intentshop);
			break;
		case R.id.member_buy:
			Intent intentbuy = new Intent(this, ReferActivity.class);
			intentbuy.putExtra(Constanct.INTENT_COLLECTOR, 2);
			startActivity(intentbuy);
			break;
		case R.id.member_product:
			Intent intentproduct = new Intent(this, ReferActivity.class);
			intentproduct.putExtra(Constanct.INTENT_COLLECTOR, 1);
			startActivity(intentproduct);
			break;
		case R.id.finished:
			reginstUser();
			((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
			break;
		case R.id.member_logout_btn:
			DataCache.getInstance().put(Constanct.ISLOGINED_KEY, null);
			findViewById(R.id.login_pre).setVisibility(VISIBLE);
			findViewById(R.id.login_after).setVisibility(GONE);
			((EditText) findViewById(R.id.password_l)).setText("");
		case R.id.txbutton:
			if(qqWeiboLogined){
				Toast.makeText(this, R.string.qq_weibo_logined, Toast.LENGTH_SHORT).show();
			}else{
				QQWeiboUtil.callAuthorizeUI(this);
			}
			break;
		case R.id.sinabutton:
			if(sinaWeiboLogined){
				Toast.makeText(this, R.string.sina_weibo_logined, Toast.LENGTH_SHORT).show();
			}else{
				SinaWeiboUtil.callAuthorizeUI(this);
			}
			break;
		default:
			break;
		}
	}
//{"keycode":"hxRN98VARF1BYUXo","userpass":"123","AccountID":24,"username":"hyz"}
	private void toLogin() {
		setContentView(R.layout.activity_main_login);
		qqWeiboImageButton = (MyImageButton) findViewById(R.id.txbutton);
		sinaWeiboImageButton = (MyImageButton) findViewById(R.id.sinabutton);
		qqWeiboImageButton.setOnClickListener(this);
		sinaWeiboImageButton.setOnClickListener(this);
		refreshQQWeiboLoginState();
		refreshSinaWeiboLoginState();
		findViewById(R.id.register).setOnClickListener(this);
		findViewById(R.id.login).setOnClickListener(this);
		findViewById(R.id.member_refer).setOnClickListener(this);
		findViewById(R.id.member_shop).setOnClickListener(this);
		findViewById(R.id.member_buy).setOnClickListener(this);
		findViewById(R.id.member_product).setOnClickListener(this);
		findViewById(R.id.member_logout_btn).setOnClickListener(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		refreshQQWeiboLoginState();
		refreshSinaWeiboLoginState();
	}
	
	
	public void refreshQQWeiboLoginState(){
		String qqWeiboUserName = QQWeiboUtil.getAuthorizeUserName(this);
		/*if (qqWeiboUserName != null
				&& !getString(R.string.qq_weibo_text).equals(qqWeiboUserName)) {*/
		if(qqWeiboUserName != null){
			qqWeiboImageButton.setIsLogin(true);
			qqWeiboLogined = true;
		} else {
			qqWeiboImageButton.setIsLogin(false);
			qqWeiboLogined = false;
		}
		mHandler.sendEmptyMessage(10001);
	}
	
	protected void showProgress() {
		if(mProgressDialog == null){
			mProgressDialog = ProgressDialog.show(this, null, getString(R.string.loading));
		}else if(!mProgressDialog.isShowing()){
			mProgressDialog.show();
		}
		new Handler().postDelayed(new Runnable() {
			
			@Override
			public void run() {
				try{
					mProgressDialog.dismiss();
				}catch (Exception e) {
				}
			}
		}, 6000);
	}
	
	public void refreshSinaWeiboLoginState(){
		String sinaWeiboUserName = SinaWeiboUtil.getAuthorizeUserName(this);
		/*if (sinaWeiboUserName != null
				&& !getString(R.string.sina_weibo_text).equals(
						sinaWeiboUserName)) {*/
		if(sinaWeiboUserName != null){
			sinaWeiboImageButton.setIsLogin(true);
			sinaWeiboLogined = true;
		} else {
			sinaWeiboImageButton.setIsLogin(false);
			sinaWeiboLogined = false;
		}
		mHandler.sendEmptyMessage(10000);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == QQWeiboUtil.RESULT && resultCode == OAuthV2AuthorizeWebView.RESULT_CODE){
			OAuthV2 oauth = (OAuthV2) data.getExtras().getSerializable("oauth");
			String msg = oauth.getMsg();
			String split[] = oauth.getMsg().split("&");
			String userName = split[split.length - 2].split("=")[1];
			
			if(QQWeiboUtil.authorize(this, userName, oauth.getAccessToken(), oauth.getOpenid(), oauth.getClientId())){
				refreshQQWeiboLoginState();
			}
		}
		
	}
	
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case 10000:
				sinaWeiboImageButton.invalidate();
				break;
			case 10001:
				qqWeiboImageButton.invalidate();
				break;
			}
		};
	};

}